package com.llp.declaresystem.interceptor;

import com.alibaba.druid.util.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @BelongsProject: declare-system
 * @BelongsPackage: com.llp.declaresystem.intercept
 * @Author: bovan
 * @Date: 2022/11/24 23:14
 * @Description:
 */
@Configuration
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("登录拦截器---------->");
        HttpSession session = request.getSession();
        Object user = session.getAttribute("userInfo");

        System.out.println("userInfo:"+user);
        if (user==null || StringUtils.equals(String.valueOf(user), "")) {
            System.out.println("未登录："+session.getId());
            //未登录跳转到登录页面
            response.sendRedirect(request.getContextPath()+"/login.html");
            return false;
//            throw new Exception("还没登录，请及时登录");
        }
        System.out.println("已登录--放行-------->");
        System.out.println(session.getId());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
